﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Aliphant.Common;
using Aliphant.Interfaces;
using Aliphant.Script.Models;

namespace Aliphant.Script
{
    public class ScriptManager : IScriptManager
    {
        public async Task ExecuteAsync(string path, dynamic? config, string[]? dlls = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var agent = ScriptAgent.ScriptAgentFactory();

            if (config != null)
            {
                agent.RegisterObject(config);
            }
            if (dlls != null && dlls.Length > 0)
            {
                agent.RegisterEnv(dlls);
            }

            var code = await ScriptAgent.LoadAsync(path);
            try
            {
                agent.Evaluate(code);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {
                //agent.Dispose();
                agent = null;
                GC.SuppressFinalize(this);
            }
        }

        public void Execute(string path, dynamic? config, string[]? dlls = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var agent = ScriptAgent.ScriptAgentFactory();

            if (config != null)
            {
                agent.RegisterObject(config);
            }
            if (dlls != null && dlls.Length > 0)
            {
                agent.RegisterEnv(dlls);
            }

            var code = ScriptAgent.Load(path);
            try
            {
                agent.Evaluate(code);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {
                //agent.Dispose();
                agent = null;
                GC.SuppressFinalize(this);
            }
        }

    }
}
